import { call, put, fork, select, take } from 'redux-saga/effects'
import { message } from 'antd'
import api from '@/api/templateEdit'
import actions,{ ADD } from '../actions/templateEdit';
import { history } from '@/route/history'

function* add() {
  try {
    const params = yield select(({ templateEditReducer: { template, remark } }) => ({ template, remark }) )
    const { isSuccess, desc } = yield call(api.addTemplateData, params)
    if(isSuccess){
      yield put(actions.addSuccess())
      history.push('/index/template')
    }else {
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.addFail())
    message.error(error.message || '添加错误')
  }
}

function* watchAdd() {
  while (true) {
    yield take(ADD)
    yield call(add)
  }
}

export default [
  fork(watchAdd)
]